package com.xiaoyu.lanling.base.push.meizu;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.meizu.cloud.pushsdk.PushManager;
import com.meizu.cloud.pushsdk.handler.MzPushMessage;
import com.meizu.cloud.pushsdk.platform.message.RegisterStatus;
import com.meizu.cloud.pushsdk.util.MzSystemUtils;
import com.xiaoyu.base.AppConfig;
import com.xiaoyu.base.push.BasePushAgent;
import com.xiaoyu.base.push.PushConstants;


import java.util.Iterator;

import in.srain.cube.request.JsonData;
import in.srain.cube.util.CLog;

public class MeizuPushAgent extends BasePushAgent {

    private static MeizuPushAgent sInstance;

    protected MeizuPushAgent() {
        super(PushConstants.PUSH_TYPE_MEIZU);
    }

    public static synchronized MeizuPushAgent getInstance() {
        if (sInstance == null) {
            sInstance = new MeizuPushAgent();
        }
        return sInstance;
    }

    @Override
    protected void tryToStartPushService(Context context) {
        super.tryToStartPushService(context);
        if (MzSystemUtils.isBrandMeizu(context)) {
            PushManager.register(context, AppConfig.flymeAppId(), AppConfig.flymeAppKey());
        }
    }

    public void onRegisterStatus(Context context, RegisterStatus registerStatus) {
        CLog.i(TAG, "onRegisterStatus message: %s", registerStatus);
        if (TextUtils.equals(registerStatus.code, RegisterStatus.SUCCESS_CODE)) {
            onRegisterSuccess(registerStatus.getPushId());
        } else {
            retryOnFail(String.valueOf(registerStatus.code));
        }
    }

    public void onNotificationClicked(Context context, MzPushMessage mzPushMessage) {
        CLog.i(TAG, "onNotificationClicked message: %s", mzPushMessage);
        onNotificationClickData(mzPushMessage.getContent());

        if (!TextUtils.isEmpty(mzPushMessage.getSelfDefineContentString())) {
            Intent intent = new Intent();
            intent.setAction("LL_PUSH_MEIZU_RECEIVER");

            JsonData jsonData = JsonData.create(mzPushMessage.getSelfDefineContentString());
            Iterator<String> keys = jsonData.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                String value = jsonData.optString(key);
                intent.putExtra(key, Uri.decode(value));
            }

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    public void onMessage(Context context, String s) {
        CLog.i(TAG, "onMessage message: %s", s);
        onPassThroughMessage(s);
    }
}
